package com.ls.lsqc.modules.sys.web;



import com.ls.lsqc.modules.sys.utils.SystemMessageUtils;
import groovy.util.ResourceException;
import freemarker.template.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ls.lsqc.common.config.Global;
import com.ls.lsqc.common.persistence.AjaxDone;
import com.ls.lsqc.common.persistence.BaseEntity;
import com.ls.lsqc.common.persistence.Page;
import com.ls.lsqc.common.utils.ResourcesUtil;
import com.ls.lsqc.common.utils.StringUtils;
import com.ls.lsqc.common.web.BaseController;
import com.ls.lsqc.modules.sys.entity.Brand;
import com.ls.lsqc.modules.sys.service.BrandService;

/**
  * @ClassName: CustomerBrandController
  * @Description: 客户品牌
  * 
  * @author 秦玉峰
  * @date 2017年04月13日 下午3:15:19
  *
  */

@Controller
@RequestMapping(value = "${adminPath}/customer/brand/")
public class CustomerBrandController extends BaseController {

	@Autowired
	// 保存 编辑 删除 方法
	private BrandService brandservice;
	
	@Autowired
	Configuration freemarkerConfiguration;
	
	
	@ModelAttribute
	public Brand get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			// 执行查询语句 查询基本信息
			return brandservice.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Brand();
		}
	}
	/**
	 * 进入一览页面
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("customer:brand:view")
	@RequestMapping(value = {"list", ""})
	public String list() {
			    
	    // 返回页面地址
	    return "modules/sys/brandList";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param brand
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("customer:brand:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Brand brand, HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {

		Map<Object, Object> listMap = new HashMap<Object, Object>();
		
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "dict");
	
		// 画面取得的检索项目
		//品牌中文
		String brandCn = brand.getBrandCn();
		//品牌英文
		String brandEn = brand.getBrandEn();

		
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 拼接字符串供分页使用
		String searchParam ="&brandCn="+brandCn+"&brandEn="+brandEn;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
	
		// 查询一览页面数据
		Page<Brand> page = brandservice.findList(new Page<Brand>(request, response), brand);
		
		// 读取系统路径
		// 读取文件生成字符串
		
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("dicts", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("Brand.ftl"), map);
		listMap.put("dict", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	 
	
	
	/**
     * 进入查看页面
     * @param brand
     * @param model
     * @return
     */
    @RequiresPermissions("customer:brand:view")
    @RequestMapping(value = "show")
    public String show(Brand brand, Model model, HttpServletRequest request, HttpServletResponse response) {
    	
    	// 执行查询方法查询子项数据
    	 List<Brand> dictList= brandservice.findListDict(brand);
    
    	 model.addAttribute("brand", brand);
    	 // 将查询结果赋值mvc model层返回jsp页面
    		 model.addAttribute("dictList", dictList);
    
        // 返回页面地址
        return "modules/sys/brandListShow";
    }
    
	/**
	 * 进入编辑页面
	 * @param brand
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customer:brand:edit")
	@RequestMapping(value = "form")
	public String form(Brand brand, Model model) {
	    
		// 新建判断 若不为null 编辑数据
		if(brand.getId()!=null){
			
	 
	     // 执行查询方法查询子项数据为0的数据
	        List<Brand> brandList=brandservice.findListDict(brand);
	        
	        // 将子项数据list 赋值给mvc model层返回给jsp页面
	        model.addAttribute("brandList", brandList);
	        
	        
	    }else{
	    	// 清空创建的子项

	    }

		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("brand", brand);
		
		// 返回页面地址
		return "modules/sys/brandEdit";
	}
	
	
	@RequiresPermissions("customer:brand:edit")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String brandCn) {

		try {
		if(brandCn != null && brandservice.getBrandCn(brandCn) == null ){
			return "true";
			
		}
        	// 数据值重名
			return "false";
		   } catch (Exception e) {
	            // 记录日志
	            logger.error(e.getMessage(), e);
	        }
				// 数据值未重名
				return "true";
	}
	
	/**
	 * 保存信息
	 * @param brand
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("customer:brand:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Brand brand, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(brand.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			Brand dictNew=get(brand.getId().toString());
			// 判断数据是否删除
            if(dictNew==null || BaseEntity.DEL_FLAG_DELETE.equals(dictNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
			
            // 排他处理
		    if(brand.getVersion()==get(brand.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	brand.setVersion(brand.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}else{
			
			// 新建版本号赋值1
			brand.setVersion(1L);
		}
		    // 保存基准数据及子项数据
			brandservice.saveBrand(brand);
			
			// 保存成功返回提示信息
	        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "dictSaveSuccess")));
	
	}
	
	/**
	 * 删除信息
	 * @param brand
	 * @param response
	 * @return
	 */
    @RequiresPermissions("customer:brand:edit")
	@RequestMapping(value = "delete")
	public String delete(Brand brand, HttpServletResponse response) {
		
		    try {
		    	
		    	// 执行逻辑删除方法
		    	brandservice.deleteBrand(brand);
            } catch (Exception e) {
                // 记录日志
                logger.error(e.getMessage(), e);
            	// 提示错误信息
                return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
            }
		    
		    // 提示删除成功信息
			return renderString(response,AjaxDone.ok(getText("dict_delete_success")));
    }
    

}
